<template>
  <div class="info-container">
    <!-- 地图区域  :org-id="orgId" -->
    <div class="map-box">
      <offline-map
        ref="offlineMapRef"
        :station-id="stationId"
        :zoom="18"
        :height="100"
        :draw-option="{ fence: true, track: true }"
        @cabinet="handleCabinet"
      />
    </div>

    <!-- 顶部标题栏 -->
    <div class="top-container">
      <div class="top-box">
        <div class="title-box">智能铁鞋信息管理平台</div>
      </div>
      <div class="user-work-box">
        <div class="workbench-box" @click="goToWorkbench">
          <div class="icon-work"></div>
          <div>工作台</div>
        </div>
        <div class="icon-work-box" @click="loadAlarmMessages">
          <div class="icon-inform">
            <n-badge
              :value="unreadAlarmCount"
              :max="99"
              :style="{ position: 'relative', bottom: '10px', left: '10px' }"
            />
          </div>
        </div>
        <div class="icon-work-box" :title="nickname">
          <n-dropdown trigger="hover" :options="userOptions" @select="handleUserOptionSelect">
            <div class="icon-profile"></div>
          </n-dropdown>
        </div>
      </div>
    </div>

    <!-- 左侧信息面板 -->
    <div class="left-box">
      <!-- 设备统计 -->
      <div class="device-stats-box">
        <div class="skate-stats-box flex">
          <div class="device-total-box">
            <div>铁鞋总数</div>
            <div class="device-total">{{ shoeTotal }}</div>
          </div>
          <div class="device-details">
            <div v-for="(item, index) in shoeStats" :key="index" class="device-details-box">
              <div class="stats-info-box">
                <div class="stats-text">{{ item.name }}</div>
                <div class="stats-num" :style="{ color: item.color }">{{ item.num }}</div>
              </div>
              <div
                :class="['halving', index !== shoeStats.length - 1 ? 'halving-image' : '']"
              ></div>
            </div>
          </div>
        </div>

        <div class="spanner-stats-box flex">
          <div class="device-total-box">
            <div>紧固器总数</div>
            <div class="device-total">{{ spannerTotal }}</div>
          </div>
          <div class="device-details">
            <div v-for="(item, index) in spannerStats" :key="index" class="device-details-box">
              <div class="stats-info-box">
                <div class="stats-text">{{ item.name }}</div>
                <div class="stats-num" :style="{ color: item.color }">{{ item.num }}</div>
              </div>
              <div
                :class="['halving', index !== spannerStats.length - 1 ? 'halving-image' : '']"
              ></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 设防作业 -->
      <div class="fortify-task-box">
        <div class="item-title-box">
          <div class="item-title-name">设防作业</div>
        </div>
        <div class="fortify-table-box">
          <div class="tabs-box">
            <div
              v-for="(tab, index) in taskTabs"
              :key="index"
              :class="['tab-name', tab.checked ? 'tab-name-activity' : '']"
              @click="selectTaskTab(tab)"
            >
              {{ tab.name }}
            </div>
          </div>
          <div class="fortify-table-container">
            <n-data-table
              v-if="taskRecords.length"
              class="fortify-table"
              :columns="taskColumns"
              :data="taskRecords"
              :row-class-name="getRowClassName"
              :row-key="(row) => row.id"
            />
            <div v-else class="not-data-box"></div>
          </div>
        </div>
      </div>

      <!-- 当班信息 -->
      <div class="watch-box">
        <div class="item-title-box">
          <div class="item-title-name">当班信息</div>
        </div>
        <div class="watch-content-box" v-if="crewData && crewData.length">
          <div class="watch-captain">
            <div class="captain-photo-box">
              <img
                :style="{ 'max-height': '100%', width: 'auto' }"
                :src="captainInfo.photo"
                alt=""
              />
            </div>
            <div class="captain-info-box">
              <div class="captain-item-box">
                <div class="captain-text">班长</div>
                <div class="captain-info">{{ captainInfo.name }}</div>
                <div class="captain-phone">{{ captainInfo.phone }}</div>
              </div>
              <div class="captain-item-box">
                <div class="captain-text" style="margin-left: 1rem">当班人数</div>
                <div class="captain-info" style="margin-left: 1.8rem">{{ captainInfo.num }}人</div>
              </div>
            </div>
          </div>
          <div class="watch-captain-member">
            <div class="team-member-box">
              <div v-for="(member, index) in teamMembers" :key="index" class="member-item-box">
                <div class="member-num-box">{{ index + 1 }}</div>
                <div class="member-text">{{ member }}</div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="watch-content-box">
          <div class="not-data-box"></div>
        </div>
      </div>
    </div>

    <!-- 中间状态展示 -->
    <div class="middle-box">
      <div class="flex gap">
        <div v-for="(item, index) in deviceIcons" :key="index" class="flex">
          <div :class="item.class" :style="{ background: item.color }"></div>
          <div class="text-box">{{ item.name }}</div>
        </div>
      </div>
      <div class="flex gap">
        <div v-for="(item, index) in shoeStates" :key="index" class="flex">
          <div :class="item.class" :style="{ background: item.color }"></div>
          <div class="text-box">{{ item.name }}</div>
        </div>
      </div>
    </div>

    <!-- 右侧统计面板 -->
    <div class="right-box">
      <!-- 防溜作业统计 -->
      <div class="antiskid-stats-box">
        <div class="item-title-box">
          <div class="item-title-name">防溜作业统计</div>
        </div>
        <div class="antiskid-content-box">
          <div class="antiskid-details">
            <div v-for="(item, index) in taskStats" :key="index" class="antiskid-details-item">
              <div
                class="antiskid-details-num"
                :style="{ 'text-shadow': '0px 0px 6px' + item.color }"
              >
                {{ item.num }}
              </div>
              <div class="antiskid-details-name" :style="{ color: item.color1 }">
                {{ item.name }}
              </div>
              <div :class="['antiskid-state-box', item.className]"></div>
            </div>
          </div>
          <div class="antiskid-stats-char-box">
            <div class="antiskid-week-box">
              <div
                :class="['antiskid-week', !isLastWeek ? 'antiskid-week-active' : '']"
                @click="toggleWeek"
              >
                本周
              </div>
              <div
                :class="['antiskid-week', isLastWeek ? 'antiskid-week-active' : '']"
                @click="toggleWeek"
              >
                上周
              </div>
            </div>
            <div id="antiskidStatsChar" style="height: 100%; width: 100%"></div>
          </div>
        </div>
      </div>

      <!-- 报警统计 -->
      <div class="alarm-stats-box">
        <div class="item-title-box">
          <div class="item-title-name">报警统计</div>
        </div>
        <div class="alarm-content-box">
          <div class="alarm-details-box">
            <div v-for="(item, index) in alarmStats" :key="index" class="alarm-details-item">
              <div class="alarm-details-item-text">{{ item.name }}</div>
              <div class="alarm-details-item-num">{{ item.num }}</div>
            </div>
          </div>
          <div class="alarm-info-box">
            <div v-if="!alarmMessages.length" class="not-data-box"></div>
            <scroll-box ref="scrollBoxRef" v-else>
              <template #forwardContent>
                <div v-for="(item, index) in alarmMessages" :key="index" class="alarm-item-box">
                  <div class="alarm-name-box" :title="item.alarmContent">
                    <div class="alarm-icon-box"></div>
                    <div>
                      <div class="alarm-name">{{ item.alarmTitle }}</div>
                      <div class="alarm-time">{{ item.createTime }}</div>
                    </div>
                  </div>
                </div>
              </template>
            </scroll-box>
          </div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="buttons-box">
      <div class="btn-box" @click="showSetDefenseModel">设防</div>
      <div class="btn-box" @click="showUnDefenseModel">撤防</div>
      <div class="btn-box" @click="showChangeModel">更换</div>
    </div>

    <!-- 模态框组件 -->
    <set-defense-model ref="setDefenseModel" @refresh="refreshData" />
    <un-defense-model ref="unDefenseModel" @refresh="refreshData" />
    <change-model ref="changeModel" @refresh="refreshData" />
    <inspection-model ref="inspectionModel" />
    <cabinet-model ref="cabinetModel" />
    <code-change-modal ref="codeChangeRef" />

    <!-- 消息中心抽屉 -->
    <n-drawer v-model:show="showMessageCenter" :default-width="'40%'" placement="right" resizable>
      <n-drawer-content title="消息中心" closable>
        <n-split
          direction="horizontal"
          :default-size="0.1"
          :resize-trigger-size="0"
          style="height: 75px"
        >
          <template #1>
            <n-tag size="large" class="tag-all" @click="filterMessages(null, '')"> 全部 </n-tag>
          </template>
          <template #2>
            <n-split direction="vertical" :resize-trigger-size="0" style="height: 92px">
              <template #1>
                <div style="display: flex">
                  <div>
                    <n-tag
                      type="error"
                      size="small"
                      style="margin-right: 5px; cursor: pointer"
                      @click="filterMessages(true, '')"
                    >
                      报警消息
                    </n-tag>
                  </div>
                  <div>
                    <n-tag
                      v-for="(item, index) in alarmCategoryTags"
                      :key="index"
                      type="info"
                      size="small"
                      style="margin-right: 2px; cursor: pointer"
                      @click="filterMessages(true, item.value)"
                    >
                      {{ item.label }}
                    </n-tag>
                  </div>
                </div>
              </template>
              <template #2>
                <div style="display: flex; padding-top: 3px">
                  <div>
                    <n-tag
                      type="warning"
                      size="small"
                      style="margin-right: 5px; cursor: pointer"
                      @click="filterMessages(false, '')"
                    >
                      提醒消息
                    </n-tag>
                  </div>
                  <div>
                    <n-tag
                      v-for="(item, index) in reminderCategoryTags"
                      :key="index"
                      type="success"
                      size="small"
                      style="margin-right: 2px; cursor: pointer"
                      @click="filterMessages(false, item.value)"
                    >
                      {{ item.label }}
                    </n-tag>
                  </div>
                </div>
              </template>
            </n-split>
          </template>
        </n-split>

        <n-list hoverable clickable>
          <n-empty
            v-if="!messageList.length"
            size="large"
            description="无数据"
            style="width: 100%"
          />
          <n-list-item
            v-for="(item, index) in messageList"
            :key="index"
            @click="markMessageAsRead(item)"
          >
            <n-badge v-if="item.isRead == 0" dot style="float: left" />
            <n-thing :title="item.informTitle" content-style="margin-top: 10px;">
              <template #description>
                <n-space size="small" style="margin-top: 4px">
                  <n-tag :type="item.alarmId ? 'error' : 'warning'" size="small">
                    {{ item.alarmId ? '报警消息' : '提醒消息' }}
                  </n-tag>
                  <n-tag :type="item.alarmId ? 'info' : 'success'" size="small">
                    {{
                      item.alarmId
                        ? getAlarmCategoryLabel(item.informCategory)
                        : getReminderCategoryLabel(item.informCategory)
                    }}
                  </n-tag>
                </n-space>
              </template>
              <div>{{ item.informContent }}</div>
              <div style="text-align: right">{{ item.sendTime }}</div>
            </n-thing>
          </n-list-item>
        </n-list>

        <div
          v-if="messageTotal > 0"
          style="float: right; background-color: white; margin-top: 1%; border-radius: 3px"
        >
          <n-pagination
            v-model:page="currentPage"
            :page-sizes="[10]"
            :item-count="messageTotal"
            @update:page="loadMessages"
          />
        </div>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, h, reactive, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';
  import { useDictStore } from '@/store/modules/dict';
  import { useMessage } from 'naive-ui';
  import * as echarts from 'echarts';
  import OfflineMap from '@/views/businessPages/comp/map/offlineMap.vue';
  import ScrollBox from './components/ScrollBox.vue';
  import SetDefenseModel from './modals/SetDefenseModel.vue';
  import UnDefenseModel from './modals/UnDefenseModel.vue';
  import ChangeModel from './modals/ChangeModel.vue';
  import InspectionModel from './modals/InspectionModel.vue';
  import CabinetModel from './modals/CabinetModel.vue';
  //   import CodeChangeModal from './modals/CodeChangeModal.vue';

  // API接口导入
  import {
    getDeviceStats,
    getTaskStats,
    getTaskStatsByTime,
    getDefensiveByStationId,
    getGroupDetailByStationId,
    getAlarmStats,
    getRecordByTaskId,
  } from '@/api/home/home';

  // 引用组件
  const offlineMapRef = ref();
  const scrollBoxRef = ref();
  const setDefenseModel = ref();
  const unDefenseModel = ref();
  const changeModel = ref();
  const inspectionModel = ref();
  const cabinetModel = ref();
  const codeChangeRef = ref();

  // 用户相关
  const userStore = useUserStore();
  const nickname = userStore.getNickname || '';
  // const orgId = userStore.getUserInfo.orgId || '';

  const userOptions = [
    { label: '修改密码', key: '1' },
    { label: '退出登录', key: '2' },
  ];

  // 路由和消息
  const route = useRoute();
  const router = useRouter();
  const message = useMessage();

  // 数据状态
  const isLastWeek = ref(false);
  const showMessageCenter = ref(false);
  const unreadAlarmCount = ref(0);
  const currentPage = ref(1);
  const messageTotal = ref(0);
  const orgId = ref('');
  const stationId = ref('');

  // 设备统计
  const shoeTotal = ref(0);
  const spannerTotal = ref(0);

  const shoeStats = ref([
    { name: '当前可用', num: 0, color: '#26C5FE' },
    { name: '防溜中', num: 0, color: '#1DFEA0' },
    { name: '防溜失效', num: 0, color: '#FFED71' },
  ]);

  const spannerStats = ref([
    { name: '当前可用', num: 0, color: '#26C5FE' },
    { name: '防溜中', num: 0, color: '#1DFEA0' },
  ]);

  // 任务统计
  const taskStats = ref([
    {
      name: '设防累计',
      num: 0,
      className: 'antiskid-state1-box',
      color: '#0066FF',
      color1: '#A6DAFF',
    },
    {
      name: '撤防累计',
      num: 0,
      className: 'antiskid-state2-box',
      color: '#26C5FE',
      color1: '#9FE2FF',
    },
    {
      name: '更换累计',
      num: 0,
      className: 'antiskid-state3-box',
      color: '#23E192',
      color1: '#94EAC7',
    },
    {
      name: '巡检累计',
      num: 0,
      className: 'antiskid-state4-box',
      color: '#ECDA66',
      color1: '#FFF6BB',
    },
  ]);

  // 报警统计
  const alarmStats = ref([
    { name: '防溜失效', num: 0 },
    { name: '低电量', num: 0 },
    { name: '电子围栏', num: 0 },
    { name: '漏放漏撤', num: 0 },
  ]);

  // 图标展示
  const deviceIcons = ref([
    { name: '紧固器', class: 'icon-spanner', color: '' },
    { name: '器具箱', class: 'icon-utensil-box', color: '' },
    { name: '铁鞋', class: 'icon-skate-left', color: '#fff' },
  ]);

  const shoeStates = ref([
    { name: '防溜途中', class: 'icon-skate-left', color: '#3C9BFF' },
    { name: '归箱途中', class: 'icon-skate-left', color: '#00FF1A' },
    { name: '防溜中', class: 'icon-skate-left', color: '#FFB800' },
    { name: '防溜失效', class: 'icon-skate-left', color: '#FF2E00' },
    { name: '失联中', class: 'icon-skate-left', color: '#8c8b8b' },
  ]);

  // 任务相关
  const taskTabs = ref([]);
  const taskRecords = ref([]);
  const taskColumns = ref([
    {
      title: '序号',
      key: 'id',
      width: 15,
      align: 'center',
      render: (row, index) => `${index + 1}`,
    },
    { title: '铁鞋编号', key: 'shoeCode', width: 60, align: 'center', ellipsis: true },
    { title: '占用股道', key: 'trackName', width: 60, align: 'center' },
    { title: '紧固器', key: 'fastenerCode', width: 50, align: 'center' },
    {
      title: '状态',
      key: 'state',
      width: 40,
      align: 'center',
      render(row) {
        return h(
          'n-tag',
          {
            style: {
              backgroundColor: row.state === 4 ? 'rgb(255,46,0,0.3)' : 'rgb(0,255,25,0.3)',
              color: row.state === 4 ? 'rgb(255,46,0)' : 'rgb(0,255,25)',
              border: row.state === 4 ? '1px solid #FF2E00' : '1px solid #00FF19',
            },
            type: row.state === 4 ? 'error' : 'success',
            size: 'small',
          },
          row.state === 4 ? '防溜失效' : '防溜中'
        );
      },
    },
  ]);

  // 当班信息
  const crewData = ref([]);
  const captainInfo = ref({
    name: '',
    phone: '',
    photo: '',
    num: 0,
  });
  const teamMembers = ref([]);

  // 消息列表
  const messageList = ref([]);
  const alarmMessages = ref([]);

  // 字典数据
  const dictStore = useDictStore();
  const alarmCategoryTags = dictStore.getAlarmCategoryTags;
  const reminderCategoryTags = dictStore.getReminderCategoryTags;

  // ECharts 图表实例
  let chartInstance = null;

  // 方法定义
  const handleCabinet = (data) => {
    cabinetModel.value?.show(data);
  };

  const goToWorkbench = () => {
    router.push('/businessPages/homepage/index');
  };

  const loadAlarmMessages = () => {
    // 加载报警消息逻辑
  };

  const handleUserOptionSelect = (key) => {
    if (key === '1') {
      codeChangeRef.value?.showModal('修改密码');
    } else if (key === '2') {
      message.info({
        title: '提示',
        content: '您确定要退出登录吗？',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
          userStore.logout().then(() => {
            message.success('已成功退出登录');
            router.push('/login');
          });
        },
      });
    }
  };

  const getRowClassName = (row, index) => {
    return index % 2 === 0 ? '' : 'row-arrows';
  };

  const selectTaskTab = (tab) => {
    taskTabs.value.forEach((t) => (t.checked = false));
    tab.checked = true;
    loadTaskRecords(tab.id);
  };

  const toggleWeek = () => {
    isLastWeek.value = !isLastWeek.value;
    loadTaskStatsByTime();
  };

  const showSetDefenseModel = () => {
    setDefenseModel.value?.show(orgId.value);
  };

  const showUnDefenseModel = () => {
    unDefenseModel.value?.show(orgId.value);
  };

  const showChangeModel = () => {
    changeModel.value?.show(orgId.value);
  };

  const refreshData = () => {
    loadData();
  };

  const filterMessages = (isAlarm, category) => {
    // 过滤消息逻辑
  };

  const markMessageAsRead = (message) => {
    // 标记消息为已读逻辑
  };

  const getAlarmCategoryLabel = (category) => {
    const item = alarmCategoryTags.find((tag) => tag.value === category);
    return item ? item.label : '';
  };

  const getReminderCategoryLabel = (category) => {
    const item = reminderCategoryTags.find((tag) => tag.value === category);
    return item ? item.label : '';
  };

  const loadMessages = (page) => {
    currentPage.value = page;
    // 加载消息逻辑
  };

  // 新增方法：加载设备统计信息
  const loadDeviceStats = async () => {
    try {
      const params = {
        stationId: stationId.value,
      };
      const res = await getDeviceStats(params);

      if (res) {
        shoeTotal.value = res.shoeTotal || 0;
        spannerTotal.value = res.spannerTotal || 0;

        // 更新铁鞋统计数据
        if (res.shoeUsable !== undefined) shoeStats.value[0].num = res.shoeUsable;
        if (res.shoeFortify !== undefined) shoeStats.value[1].num = res.shoeFortify;
        if (res.shoeFailure !== undefined) shoeStats.value[2].num = res.shoeFailure;

        // 更新紧固器统计数据
        if (res.spannerUsable !== undefined) spannerStats.value[0].num = res.spannerUsable;
        if (res.spannerFortify !== undefined) spannerStats.value[1].num = res.spannerFortify;
      }
    } catch (error) {
      console.error('加载设备统计信息失败:', error);
    }
  };

  // 新增方法：加载任务统计信息
  const loadTaskStats = async () => {
    try {
      const params = {
        stationId: stationId.value,
      };
      const res = await getTaskStats(params);

      if (res) {
        taskStats.value[0].num = res.defenseTotal || 0;
        taskStats.value[1].num = res.unDefenseTotal || 0;
        taskStats.value[2].num = res.changeTotal || 0;
        taskStats.value[3].num = res.inspectionTotal || 0;
      }
    } catch (error) {
      console.error('加载任务统计信息失败:', error);
    }
  };

  // 新增方法：按时间加载任务统计信息（用于图表）
  const loadTaskStatsByTime = async () => {
    try {
      // 计算时间范围
      const now = new Date();
      let startTime, endTime;

      if (isLastWeek.value) {
        // 上周
        const lastWeekStart = new Date(now);
        lastWeekStart.setDate(now.getDate() - now.getDay() - 6);
        const lastWeekEnd = new Date(lastWeekStart);
        lastWeekEnd.setDate(lastWeekStart.getDate() + 6);

        startTime = formatDate(lastWeekStart, 'yyyy-MM-dd');
        endTime = formatDate(lastWeekEnd, 'yyyy-MM-dd');
      } else {
        // 本周
        const thisWeekStart = new Date(now);
        thisWeekStart.setDate(now.getDate() - now.getDay() + 1);
        const thisWeekEnd = new Date(thisWeekStart);
        thisWeekEnd.setDate(thisWeekStart.getDate() + 6);

        startTime = formatDate(thisWeekStart, 'yyyy-MM-dd');
        endTime = formatDate(thisWeekEnd, 'yyyy-MM-dd');
      }

      const params = {
        stationId: stationId.value,
        startTime: startTime,
        endTime: endTime,
      };

      const res = await getTaskStatsByTime(params);

      if (res && chartInstance) {
        // 更新图表数据
        const option = {
          xAxis: {
            data: res.dates || [],
          },
          series: [
            { data: res.defenseTasks || [] },
            { data: res.unDefenseTasks || [] },
            { data: res.changeTasks || [] },
            { data: res.inspectionTasks || [] },
          ],
        };
        chartInstance.setOption(option);
      }
    } catch (error) {
      console.error('加载时间任务统计信息失败:', error);
    }
  };

  // 新增方法：加载防溜作业任务
  const loadDefensiveTasks = async () => {
    try {
      const params = {
        stationId: stationId.value,
      };
      const res = await getDefensiveByStationId(params);

      if (res && Array.isArray(res) && res.length > 0) {
        // 构造任务标签
        const tabs = res.map((taskId, index) => ({
          id: taskId,
          name: `作业${index + 1}`,
          checked: index === 0,
        }));

        taskTabs.value = tabs;

        // 默认加载第一个任务的记录
        if (tabs.length > 0) {
          loadTaskRecords(tabs[0].id);
        }
      }
    } catch (error) {
      console.error('加载防溜作业任务失败:', error);
    }
  };

  // 新增方法：加载任务记录
  const loadTaskRecords = async (taskId) => {
    try {
      const params = {
        taskId: taskId,
      };
      const res = await getRecordByTaskId(params);
      
      taskRecords.value = res || [];
    } catch (error) {
      console.error('加载任务记录失败:', error);
      taskRecords.value = [];
    }
  };

  // 新增方法：加载班组详情
  const loadGroupDetail = async () => {
    try {
      const params = {
        stationId: stationId.value,
      };
      const res = await getGroupDetailByStationId(params);

      if (res && Array.isArray(res) && res.length > 0) {
        crewData.value = res;

        // 查找班长信息
        const captain = res.find((item) => item.monitor);
        if (captain) {
          captainInfo.value.name = captain.memberName || '';
          captainInfo.value.phone = captain.phone || '';
          captainInfo.value.photo = captain.photoPath || '';
          captainInfo.value.num = res.length;
        }

        // 其他成员
        const members = res.filter((item) => !item.monitor);
        teamMembers.value = members.map((item) => item.memberName || '');
      }
    } catch (error) {
      console.error('加载班组详情失败:', error);
    }
  };

  // 新增方法：加载报警统计
  const loadAlarmStats = async () => {
    try {
      const params = {
        stationId: stationId.value,
      };
      const res = await getAlarmStats(params);

      if (res) {
        alarmStats.value[0].num = res.ja1Num || 0; // 防溜失效
        alarmStats.value[1].num = res.sa2Num || 0; // 低电量
        alarmStats.value[2].num = res.sa1Num || 0; // 电子围栏
        alarmStats.value[3].num = res.ja2Num || 0; // 漏放漏撤
      }
    } catch (error) {
      console.error('加载报警统计失败:', error);
    }
  };

  // 格式化日期
  const formatDate = (date, format) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return format.replace('yyyy', year).replace('MM', month).replace('dd', day);
  };

  // 初始化图表
  const initChart = () => {
    nextTick(() => {
      const chartDom = document.getElementById('antiskidStatsChar');
      if (chartDom) {
        chartInstance = echarts.init(chartDom);
        const option = {
          title: {
            text: '周统计',
            textStyle: {
              color: '#A4D5FF',
              fontWeight: 'normal',
            },
            left: 0,
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
            },
          },
          legend: {
            top: 30,
            itemGap: 20,
            textStyle: {
              color: '#ffffff',
            },
          },
          grid: {
            left: '3%',
            right: '6%',
            bottom: '5%',
            top: '30%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            offset: 5,
            axisLine: {
              show: false,
              lineStyle: {
                color: '#ffffff',
              },
            },
            data: [],
            axisTick: {
              show: false,
            },
          },
          yAxis: {
            type: 'value',
            name: '（次）',
            offset: 10,
            axisLine: {
              show: false,
              lineStyle: {
                color: '#ffffff',
              },
            },
            minInterval: 1,
            splitLine: {
              show: true,
              lineStyle: {
                color: 'rgb(147,213,255,0.2)',
              },
            },
            lineStyle: {
              color: ['#10295A'],
            },
          },
          series: [
            {
              name: '设防',
              type: 'bar',
              stack: 'Ad',
              barWidth: 20,
              data: [],
              itemStyle: {
                color: '#1862C9',
              },
            },
            {
              name: '撤防',
              type: 'bar',
              stack: 'Ad',
              barWidth: 20,
              data: [],
              itemStyle: {
                color: '#26C5FE',
              },
            },
            {
              name: '更换',
              type: 'bar',
              stack: 'Ad',
              barWidth: 20,
              data: [],
              itemStyle: {
                color: '#2EFBA5',
              },
            },
            {
              name: '巡检',
              type: 'bar',
              stack: 'Ad',
              barWidth: 20,
              data: [],
              itemStyle: {
                color: '#FFED71',
              },
            },
          ],
        };
        chartInstance.setOption(option);
      }
    });
  };

  // 加载所有数据
  const loadData = async () => {
    await Promise.all([
      loadDeviceStats(),
      loadTaskStats(),
      loadTaskStatsByTime(),
      loadDefensiveTasks(),
      loadGroupDetail(),
      loadAlarmStats(),
    ]);
  };

  // 组件挂载
  onMounted(() => {
    // 监听用户信息变化
    // const unwatch = watch(
    //   () => userStore.getUserInfo,
    //   (newUserInfo) => {
    //     if (newUserInfo && newUserInfo.stationId) {
    //       orgId.value = newUserInfo.orgId || '';
    //       stationId.value = newUserInfo.stationId || '';

    //       // 当获取到有效的 stationId 后加载数据
    //       if (stationId.value) {
    //         // 初始化图表
    //         initChart();
    //         // 加载数据
    //         loadData();
    //         // 停止监听
    //         unwatch();
    //       }
    //     }
    //   },
    //   { immediate: true, deep: true }
    // );

    // // 初始检查
    // const userInfo = userStore.getUserInfo;
    // if (userInfo && userInfo.stationId) {
    //   orgId.value = userInfo.orgId || '';
    //   stationId.value = userInfo.stationId || '';

    //   if (stationId.value) {
    //     // 初始化图表
    //     initChart();
    //     // 加载数据
    //     loadData();
    //   }
    // }

    // // 
    orgId.value = userStore.getUserInfo.orgId || '';
    // orgId.value = routeParams.orgId || '';
    stationId.value = userStore.getUserInfo.stationId || '';
    // routeParams.stationId || '';

    // 初始化图表
    initChart();

    if ('' != stationId.value) {
      // 加载数据
      loadData();
    }
  });

  // 组件卸载前
  onBeforeUnmount(() => {
    if (chartInstance) {
      chartInstance.dispose();
    }
  });

  // 窗口大小改变时重置图表
  window.addEventListener('resize', () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  });
</script>

<style scoped>
  @import './index.css';
  /* 表格行样式增强 */
  /* 设备作业表格样式增强 */

  /* 表格修改 */
  .fortify-table :deep(.n-data-table) {
    border: 0 !important;
    background: transparent !important;
  }

  .fortify-table :deep(.n-data-table-wrapper) {
    border: 0 !important;
    border-top: 1px solid #1b7ab1 !important;
    background: transparent !important;
  }

  .fortify-table :deep(.n-data-table-table) {
    background: transparent !important;
    border: 0 !important;
  }

  .fortify-table :deep(.n-data-table-thead) {
    background: transparent !important;
    border: 0 !important;
  }

  .fortify-table :deep(.n-data-table-tbody) {
    background: transparent !important;
  }

  .fortify-table :deep(.n-data-table-tr) {
    background-color: transparent !important;
    border: 0 !important;
  }

  .fortify-table :deep(.n-data-table-th) {
    background: rgb(0 111 214 / 30%) !important;
    font-size: 0.88rem;
    color: #78c1ff;
    border: 0 !important;
    border-bottom: 0 !important;
  }

  .fortify-table :deep(.n-data-table-td) {
    color: #fff;
    background-color: transparent !important;
    border: 0 !important;
    border-bottom: 0 !important;
  }

  .fortify-table :deep(.n-data-table-tr:not(.n-data-table-tr--summary):hover) {
    background-color: transparent !important;
  }

  .fortify-table :deep(.n-data-table-tr:not(.n-data-table-tr--summary):hover > .n-data-table-td) {
    background-color: transparent !important;
  }

  /* 斑马线 */
  .fortify-table :deep(.row-arrows) {
    background: linear-gradient(
      90deg,
      rgba(75, 186, 255, 0.2) 0%,
      rgba(75, 186, 255, 0) 100%
    ) !important;
    border-bottom: 1px solid #ffffff !important;
  }

  /* 移除所有可能的边框 */
  .fortify-table :deep(.n-data-table.n-data-table--bordered) {
    border: 0 !important;
  }

  .fortify-table :deep(.n-data-table.n-data-table--bordered .n-data-table-wrapper) {
    border: 0 !important;
    border-top: 1px solid #1b7ab1 !important;
    background: transparent !important;
  }

  .fortify-table :deep(.n-data-table.n-data-table--single-line) {
    border: 0 !important;
  }

  .fortify-table :deep(.n-data-table.n-data-table--single-column) {
    border: 0 !important;
  }
</style>
